import warnings
import time
import subprocess
from paddleocr import PaddleOCR
from PIL import Image


warnings.filterwarnings("ignore")

# 定义装饰器,用于测时间开销
def time_calc(func):
    def wrapper(*args, **kargs):
        start_time = time.time()
        f = func(*args, **kargs)
        exec_time = time.time() - start_time
        print("func.name:{}\texec_time:{}".format(func.__name__, exec_time))
        return f
    return wrapper

def adb_tap(x, y):
    command = [adb_path, 'shell', 'input', 'tap', str(x), str(y)]
    try:
        result = subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        print(f"Clicked at coordinates: ({x}, {y})")
    except subprocess.CalledProcessError as e:
        print(f"Failed to tap: {e.stderr.decode().strip()}")


def ocr_return_to_success():
    crop_screenshot('screen.png', 'screen1.png', (100, 650, 880, 820))
    text = ocr.ocr("screen1.png", cls=True)
    print(text)

    if text == [None]:
        return

    length = len(text[0])
    if length in [0,1,4,5,6,7]:
        adb_tap(540, 1500)
        time.sleep(0.2)
        adb_tap(900, 2300)
        time.sleep(0.5)
        adb_tap(540, 2000)
        return 0

    if text[0][1][1][0][0] in ["胜","生"]:
        return 0

    if "场" in text[0][1][1][0]:
        return 0

    if text[0][0][1][0] in ["?","？.","？","?."]:
        return 0


    if text[0][1][1][0] not in  ["?","？.","？","?."]:
        print(f'num1:{text[0][0][1][0]}\nnum2:{text[0][1][1][0]}')
        num1 = text[0][0][1][0]
        num2 = text[0][1][1][0]

    elif text[0][1][1][0] in ["?","？.","？","?."]:
        if length == 2:
            num1 = 0
            num2 = 0
        if length == 3:
            print(f'num1:{text[0][0][1][0]}\nnum2:{text[0][2][1][0]}')
            num1 = text[0][0][1][0]
            num2 = text[0][2][1][0]
    else:
        num1 = "0.0"
        num2 = "0.0"
    num1 = str(num1)
    num2 = str(num2)
    num1 = num1.replace("L","1")
    num2 = num2.replace("L","1")
    num1 = num1.replace("V", "20")
    num2 = num2.replace("V", "20")
    num1 = num1.replace("N", "8")
    num2 = num2.replace("n", "12")
    num1 = num1.replace("n", "12")
    num2 = num2.replace("N", "8")
    num1 = num1.replace("O", "0")
    num2 = num2.replace("O", "0")
    num1 = num1.replace(".", "")
    num2 = num2.replace(".", "")
    try:

        num1 = float(num1)
        num2 = float(num2)
    except:
        num1 = 1
        num2 = 2
    print(num1)

    print(num2)
    if num1>num2:
        suc = ">"
        # 大于符号
        swipe(880, 1650, 100, 1450)
        swipe(880, 1650, 100, 1750)

    elif num1<num2:
        suc = "<"
        # 小于符号
        swipe(880, 1450, 100, 1650)
        swipe(100, 1650, 880, 1750)
    else:
        suc = "="
        # 等于符号
        swipe(100, 1450, 880, 1450)
        swipe(100, 1750, 880, 1750)
    time.sleep(0.28)
    print(f'{num1}{suc}{num2}')
    # for i in text[0]:
    #     num1 = i[1][0]
    #     if i[1][0] in ["?","？"]:



# 滑动操作
def swipe(x1, y1, x2, y2, duration=2):
    command = [adb_path, 'shell', 'input', 'swipe', str(x1), str(y1), str(x2), str(y2), str(duration)]
    result = subprocess.run(command)
    if result.returncode == 0:
        pass
        # print(f"Swiped from ({x1}, {y1}) to ({x2}, {y2}) in {duration} ms")
    else:
        print("Failed to swipe")

# 保存屏幕截图
@time_calc
def capture_screenshot(output_file='screen.png'):
    # 使用 ADB 的完整路径
    command = [adb_path, 'exec-out', 'screencap', '-p']
    with open(output_file, 'wb') as f:
        # 运行 ADB 命令并保存截图到文件
        result = subprocess.run(command, stdout=f)
    if result.returncode == 0:
        ocr_return_to_success()

    else:
        pass
        print("Failed to capture screenshot")

# 裁剪截图
def crop_screenshot(input_file, output_file, crop_area):
    """
    裁剪截图中的特定区域
    :param input_file: 输入的完整屏幕截图文件路径
    :param output_file: 输出的裁剪后图片文件路径
    :param crop_area: 裁剪区域 (left, top, right, bottom)
    """
    try:
        with Image.open(input_file) as img:
            cropped_img = img.crop(crop_area)
            cropped_img.save(output_file)

            # print(f"Cropped screenshot saved to {output_file}")
    except Exception as e:
        print(f"Failed to crop screenshot: {e}")


if __name__ == '__main__':
    ocr = PaddleOCR(use_angle_cls=True, use_gpu=True)
    adb_path = r'D:\PycharmProjects\abd_suse\platform-tools-latest-windows\platform-tools\adb.exe'

    while True:
        isopen=input("是否开始：输入任意键开始，q退出程序")
        if isopen=='q':
            break
        else:
            for i in range(20000):
                capture_screenshot('screen.png')


    print("程序结束")









